using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using AvaloniaUiKit.SampleApp.Views;
using AvaloniaUiKit.SampleApp.ViewLocators;
using Microsoft.Extensions.DependencyInjection;
using System;
using HanumanInstitute.MvvmDialogs;
using HanumanInstitute.MvvmDialogs.Avalonia;
using CommunityToolkit.Mvvm.DependencyInjection;
using AvaloniaUiKit.SampleApp.ViewModels.Pages;

namespace AvaloniaUiKit.SampleApp
{
    public partial class App : Application
    {
        private IDialogService? _dialogService;

        public override void Initialize()
        {
            AvaloniaXamlLoader.Load(this);
        }

        public override void OnFrameworkInitializationCompleted()
        {
            // Configure MvvmDialogs
            var services = new ServiceCollection();
            
            // Register the dialog service with our custom view locator
            services.AddSingleton<IDialogService>(_ => new DialogService(
                new DialogManager(
                    viewLocator: new MvvmDialogsViewLocator(),
                    dialogFactory: new DialogFactory().AddDialogHost().AddMessageBox()
                )
            ));
            
            services.AddSingleton<MvvmDialogsPageViewModel>();
            var serviceProvider = services.BuildServiceProvider();
            Ioc.Default.ConfigureServices(serviceProvider);
            _dialogService = serviceProvider.GetRequiredService<IDialogService>();
            
            // Set the dialog service for the entire application
            if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
            {
                var mainWindow = new MainWindow();
                desktop.MainWindow = mainWindow;
                
                // Store the dialog service in the window's resources for easy access
                mainWindow.Resources.Add("DialogService", _dialogService);
            }

            base.OnFrameworkInitializationCompleted();
        }
    }
} 